var express = require("express"); //web服务框架
var bodyParser = require("body-parser"); //请求体解析
var {student,news} = require("./db")

var app = express();

app.use(express.static("www"));

//cors
app.all('*', function(req, res, next){
	res.header("Access-Control-Allow-Origin", "*"); //允许所有请求源
	res.header("Access-Control-Allow-Headers", "*"); //允许所有请求头
	res.header("Access-Control-Allow-Methods", "*"); //允许所有请求方法
	next();
})

app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

app.get("/news/page/:pageNo/:pageSize", function(req, res){
	console.log(req.params)
	var pageNo = req.params.pageNo; //起始页，从0开始
	var pageSize = parseInt(req.params.pageSize); //每页的记录条数
	var skipCount = pageNo * pageSize; //跳过的记录数
	news.find({})
		.limit(pageSize)
		.skip(skipCount)
		.exec(function(error, data) {
		if(error) {
			res.json({
				message:error
			})
		} else {
			res.json({
				message:"success",
				data:data
			})
		}
	})
})

app.get("/news/all", function(req, res){
	news.find({}).exec(function(error, data){
		if(error) {
			res.json({
				message:"error"
			})
		} else {
			res.json({
				message:"success",
				data:data
			})
		}
	})
})

app.get("/student/all", function(req, res){
	student.find({}).exec(function(error, data){
		if(error) {
			res.json({
				message:"error"
			})
		} else {
			res.json({
				message:"success",
				data:data
			})
		}
	})
})

app.put("/student/upd", function(req, res){
	var where = {_id:req.body.id}
	var updateStr = {
		$set: {
			name: req.body.name,
			sex: req.body.sex,
			age: req.body.age,
			phone: req.body.phone,
			email: req.body.email
		}
	}
	student.update(where, updateStr, function(error){
		if (error) {
			res.json({
				message:"error"
			})
		} else {
			res.json({
				message:"success"
			})
		}
	})
})

app.delete("/student/del", function(req, res){
	student.remove({_id:req.body.id}, function(error){
		if (error) {
			res.json({
				message:"error"
			})
		} else {
			res.json({
				message:"success"
			})
		}
	})
})

app.post('/student/add', function(req, res){
	// console.log(req.body)
	//创建一个entity
	var stu = new student({
		name: req.body.name,
		sex: req.body.sex,
		age: req.body.age,
		phone: req.body.phone,
		email: req.body.email
	})

	stu.save(function(error){
		if (error){
			res.json({
				"message":"error"
			})
		} else {
			res.json({
				"message":"success"
			})
		}
	})
})

app.listen(3000, ()=>{
	console.log("Server started responding on port 3000.");
})